﻿using System;
using System.Reflection;

namespace Gqq.Csharpindepth.Basic
{
    public class TestAttributes
    {
        [MethodDs(MethodName = "Test1", IsOutdate = false, Author = "Gqq")]
        public void Test1()
        {
            Console.WriteLine("test1");
        }

        [MethodDs(MethodName = "Test2", IsOutdate = true, Author = "Gqq")]
        public void Test2()
        {
            Console.WriteLine("test2");
        }
        [MethodDs(MethodName = "Test3", IsOutdate = false, Author = "Gqq")]
        public void Test3()
        {
            Console.WriteLine("test3");
        }

        public static void DoTest()
        {
            var t = typeof (TestAttributes);
// ReSharper disable PossibleNullReferenceException
            //对于没有参数的构造函数的调用办法。
            //通过GetConstructor获得构造函数信息。然后通过Invoke执行构造函数。
            var obj = t.GetConstructor(Type.EmptyTypes).Invoke(null);
// ReSharper restore PossibleNullReferenceException
            //获得该类型包含的所有的方法。(DeclaredOnly表示只是生命的函数)
            MethodInfo[] methods = t.GetMethods();

            foreach (MethodInfo methodInfo in methods)
            {
                var attr = Attribute.GetCustomAttribute(methodInfo, typeof (MethodDsAttribute)) as MethodDsAttribute;
                if (attr != null)
                {
                    if (!attr.IsOutdate)
                        methodInfo.Invoke(obj, null);
                    else
                        Console.WriteLine("类{0}方法{1}已经过期", t.FullName, methodInfo.Name);
                }
                else
                    Console.WriteLine(methodInfo.Name + "没有取得MethodDsAttribute自定义属性");
            }
        }

    }
}
